﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using System.Collections.Generic;

namespace V2TEK.NET.SH.Silverlight.Charts.GanttHelper
{
    public static class TaskDescriptorUtil
    {
        public static ObservableCollection<ITaskDescriptor> ConvertXElementsToTaskDescriptors(IEnumerable<XElement> elements, ITaskDescriptor descriptor, Dictionary<string,string> attrs)
        {
            ObservableCollection<ITaskDescriptor> tasks = new ObservableCollection<ITaskDescriptor>();
            foreach(XElement element in elements)
            {
                tasks.Add(ConvertXElementToTaskDescriptor(element, descriptor, attrs));
            }
            return tasks;
        }

        public static ITaskDescriptor ConvertXElementToTaskDescriptor(XElement element, ITaskDescriptor descriptor, Dictionary<string, string> attrs)
        {
            ITaskDescriptor task = descriptor.Clone();

            XName name = XName.Get(attrs[AbstractTaskDescriptor.TASKNAME_PROPERTY]);
            task.TaskName = element.Attribute(name).Value;

            name = XName.Get(attrs[AbstractTaskDescriptor.STARTDATE_PROPERTY]);
            task.StartDate = Convert.ToDateTime(element.Attribute(name).Value);

            name = XName.Get(attrs[AbstractTaskDescriptor.ENDDATE_PROPERTY]);
            task.EndDate = Convert.ToDateTime(element.Attribute(name).Value);

            name = XName.Get(attrs[AbstractTaskDescriptor.RESOURCE_PROPERTY]);
            task.Resource = new HumanResource(element.Attribute(name).Value);

            name = XName.Get(attrs[AbstractTaskDescriptor.COMPLETE_PERCENT_PROPERTY]);
            task.PercentComplete = Convert.ToSingle(element.Attribute(name).Value);
            return task;
        }

        public static ObservableCollection<ITaskDescriptor> RecurrConvertXElementsToTaskDescriptors(IEnumerable<XElement> elements, ITaskDescriptor descriptor, Dictionary<string, string> attrs)
        {
            ObservableCollection<ITaskDescriptor> tasks = new ObservableCollection<ITaskDescriptor>();
            foreach (XElement element in elements)
            {
                ITaskDescriptor task = ConvertXElementToTaskDescriptor(element, descriptor, attrs);
                task.Children = RecurrConvertXElementsToTaskDescriptors(element.Elements(),descriptor,attrs);
                tasks.Add(task);
            }
            return tasks;
        }
    }
}
